package com.oocl.pmsystem.controller.impl;

import com.oocl.pmsystem.bean.Command;
import com.oocl.pmsystem.bean.Person;
import com.oocl.pmsystem.bean.comparator.impl.PersonIDComparator;
import com.oocl.pmsystem.bean.comparator.impl.PersonNameComparator;
import com.oocl.pmsystem.bean.condition.Condition;
import com.oocl.pmsystem.bean.condition.UpdateCondition;
import com.oocl.pmsystem.controller.CommandProcessable;
import com.oocl.pmsystem.db.PersonListFactory;
import com.oocl.pmsystem.db.SuperLinkedList;
import com.oocl.pmsystem.model.DBConnection;
import com.oocl.pmsystem.model.impl.PersonDBConnection;
import com.oocl.pmsystem.view.delegate.PMSystemDelegate;

/**
 * 账户资料管理员
 * 
 * 有一个数据结构为自定义链表的数据存取和管理 对象， 并且管理的数据类型是：Person
 * 
 * @author WUJA13
 * 
 */
public class PersonMsgController implements CommandProcessable{

	///持有View层引用
	private PMSystemDelegate mView;
	///持有Model层引用
	private DBConnection<Person> mDBConnection;
	
	
	public PersonMsgController() {
		this.mDBConnection = new PersonDBConnection();
	}

	public void setViewDelegate(PMSystemDelegate delegate) {
		this.mView = delegate;
	}

	@Override
	public boolean dealWithCommand(Command command) {
		
		if (command == null) {
			this.mView.finishProcessCommand(helpTips(command), false);
			return true;
		}
		switch (command.getCommandHead()) {
		case "L":// /查看用户信息
			query(command);
			break;
		case "A":// /添加用户信息
			if (add(command))
				this.mView.finishProcessCommand("添加成功", false);
			else
				this.mView.finishProcessCommand("添加失败", false);
			break;
		case "D":// /删除用户信息
			if (delete(command))
				this.mView.finishProcessCommand("删除成功", false);
				
			else
				this.mView.finishProcessCommand("删除失败", false);
				
			break;

		case "U":// /更新用户信息
			if (update(command))
				this.mView.finishProcessCommand("更新成功", false);
				
			else
				this.mView.finishProcessCommand("更新失败，可能该客户信息不存在", false);
			break;

		case "O":// / 排序
			sort(command);
		case "H":// 帮助
			this.mView.finishProcessCommand(helpTips(command), false);
			break;

		case "Q":// 退出
			this.mView.finishProcessCommand("退出程序", true);
			break;
		default:
				this.mView.finishProcessCommand(helpTips(null), false);
				break;
		}
		return true;
	}

	private String helpTips(Command command) {
		String helpL = "L: 输出客户信息，如 `L name:ming`或直接`L`输出全部";
		String helpA = "A: 添加客户信息， 如 `A name:ming, sex: male`";
		String helpD = "D: 根据id删除 ，如 `D 12`";
		String helpU = "U: 根据客户id修改客户信息 ，如 `U 12 name:new_name, sex:male`";
		String helpO = "O: 根据用户id排序 ： 如 `O 12`";
		String helpQ = "Q: 退出程序";
		String helpH = "H: 查看帮助";
		if (command==null || command.getCommandOptions() == null)
			return new StringBuilder().append(helpL).append("\n").append(helpA).append("\n").append(helpD).append("\n")
					.append(helpU).append("\n").append(helpO).append("\n").append(helpH).append("\n").append(helpQ)
					.toString();

		else {
			switch (command.getCommandOptions()[0]) {
			case "L":
				return helpL;
			case "A":
				return helpA;
			case "D":
				return helpD;
			case "U":
				return helpU;
			case "O":
				return helpO;
			case "Q":
				return helpQ;
			default:
				return helpH;
			}
		}
	}

	private boolean add(Command command) {
		String[] options = command.getCommandOptions();
		final String[] keys = command.getCommandKeys();
		final String[] values = command.getCommandValues();
		if (keys == null || keys.length == 0 || values == null || values.length == 0 || keys.length != values.length) {
			return false;
		}
		// /开始插入
		Person person = new Person();
		for (int i = 0; i < keys.length; i++) {
			switch (keys[i]) {
			case "name":
				person.setName(values[i]);
				break;
			case "address":
				person.setAddress(values[i]);
				break;

			case "phone":
				person.setPhone(values[i]);
				break;
			case "sex":
				person.setSex(values[i]);
				break;
			case "birthday":
				person.setBirthday(values[i]);
				break;
			default:
				return false;
			}
		}
		System.out.println("要插入的person信息:" + person);
		if (person.getName() == null || person.getName().length() == 0)
			return false;
		this.mDBConnection.add(person);
		return true;
	}

	private boolean query(Command command) {
		final String[] keys = command.getCommandKeys();
		final String[] values = command.getCommandValues();
		Person[] list = null;
		if (keys == null || keys.length == 0 || values == null || values.length == 0 || values.length!=keys.length) {
			list = this.mDBConnection.query(null);
			return checkListAndOutput(list);
		}
		// //动态给定具体的查询条件
		list = this.mDBConnection.query(new Condition<Person>() {

			@Override
			public boolean match(Person value) {
				for (int i = 0; i < keys.length; i++) {
					switch (keys[i]) {
					case "id":
						if (!values[i].equals(value.getId() + ""))
							return false;
						break;
					case "name":
						if (!value.getName().equals(values[i]))
							return false;
						break;
					case "address":
						if (!value.getAddress().equals(values[i]))
							return false;
						break;
					case "phone":
						if (!value.getPhone().equals(values[i]))
							return false;
						break;
					case "sex":
						if (!value.getSex().equals(values[i]))
							return false;
						break;
					default:
						return true;
					}
				}
				return true;
			}

		});
		return checkListAndOutput(list);// //打印
	}

	private boolean delete(Command command) {
		final String[] options = (command.getCommandOptions());
		if (options == null || options.length == 0) {
			return false;
		}
		return (this.mDBConnection.delete(new Condition<Person>() {

			@Override
			public boolean match(Person value) {
				if ((value.getId() + "").equals(options[0]))
					return true;
				else
					return false;
			}
		}));
	}

	private boolean update(Command command) {

		String[] options = command.getCommandOptions();
		final String[] keys = command.getCommandKeys();
		final String[] values = command.getCommandValues();
		if (options == null || options.length == 0 || keys == null || keys.length == 0 || values == null
				|| values.length == 0 || keys.length != values.length) {
			return false;
		}
		// /String 转 Integer
		final Integer id = Integer.valueOf(options[0]);
		if (id == null) {
			return false;
		}
		// /开始更新
		return this.mDBConnection.update(new UpdateCondition<Person>() {
			@Override
			public boolean match(Person value) {
				if (value.getId() == id) {
					return true;
				} else
					return false;
			}

			@Override
			public Person onUpdate(Person obj) {
				for (int i = 0; i < keys.length; i++) {
					switch (keys[i]) {
					case "name":
						obj.setName(values[i]);
						break;
					case "address":
						obj.setAddress(values[i]);
						break;

					case "phone":
						obj.setPhone(values[i]);
						break;
					case "sex":
						obj.setSex(values[i]);
						break;
					}
				}
				return obj;
			}
		});
	}

	private boolean sort(Command command) {
		String[] options = command.getCommandOptions();
		Person[] list = null;
		if (options == null || options.length == 0) {// //默认： 按照用户id排序
			list = this.mDBConnection.sort(new PersonIDComparator());
			return checkListAndOutput(list);
		} else {
			switch (options[0]) {
			case "id":// /根据 id 排序
				list = this.mDBConnection.sort(new PersonIDComparator());
				break;
			case "name":// / 根据 name 排序
				list = this.mDBConnection.sort(new PersonNameComparator());
				break;
			}
		}
		return checkListAndOutput(list);
	}

	/**
	 * 遍历结果数组
	 * 
	 * @param list
	 *            结果数组
	 * @return 数组是否存在
	 */
	private boolean checkListAndOutput(Person[] list) {
		if(this.mView!=null) {
		if (list == null || list.length == 0) 
				this.mView.finishProcessCommand("查询失败", false);
		else {
			for (Person person : list) {
				if (person != null) {
					this.mView.finishProcessCommand(person.toString(), true);
				}
			}
			this.mView.finishProcessCommand(null, false);
		}
		}
		return true;
	}


}
